//
//  HomeView.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/20.
//

import SwiftUI

struct HomeView: View {
    @State private var showPortfolio: Bool = false

    @EnvironmentObject private var vm: HomeViewModel // 使用主函数定义的vm

    @State private var showPortfolioView: Bool = false // new sheet

    @State private var selectedCoin: CoinModel? = nil // 选择的详情coin

    @State private var showSettingView = false

    @State private var showDetailView = false

    var body: some View {
        ZStack {
            // background
            Color.theme.background
                .ignoresSafeArea()
                .sheet(isPresented: $showPortfolioView, content: {
                    // 使用sheet的方式创建另一页面,多个sheet不能放同一层级
                    PortfolioView()
                        .environmentObject(vm)
                })

            // Content Layer
            VStack {
                // extension  more readable
                // 所有过渡动画都有$showPortfolio激活，包装在Heder的按钮上
                homeHeader

                HomeStatsView(showPortfolio: $showPortfolio)

                SearchBarView(text: $vm.searchText)

                columnTitle

                if !showPortfolio {
                    allCoinsList
                        .transition(.move(edge: .leading))
                } else {
                    ZStack(alignment: .top) {
                        if vm.portfolioCoins.isEmpty {
                            portfolioEmptyText
                        } else {
                            portfolioCoinsList
                        }
                    }
                    .transition(.move(edge: .trailing))
                }

                Spacer(minLength: 0)
            }
            .sheet(isPresented: $showSettingView, content: {
                SettingView()
            })
        }
        .background(
            // 为整体 建立一个link，从而实现懒加载？？
            // 有待 优化！！！！！！！！！！！！！！！！！！！！！！！！！——+——+——+————+——+——+——+——
            NavigationLink(isActive: $showDetailView, destination: {
                DetailLoadingView(coin: $selectedCoin)
            }, label: {
                EmptyView()
            })
        )
    }
}

#Preview {
    NavigationStack {
        HomeView()
            .toolbar(.hidden)
    }
    .environmentObject(Preview.dev.homeVM) // 为了让预览有效果，这里在extion中定义了HomeViewModel
}

extension HomeView {
    private var portfolioEmptyText: some View {
        Text("You haven't added any coins to your portfolio yet. Click the + to get start🥳")
            .font(.headline)
            .multilineTextAlignment(.center)
            .fontWeight(.medium)
            .padding()
            .padding(.top, 100)
            .foregroundStyle(.secondaryText)
    }

    private var homeHeader: some View {
        HStack {
            CircleButtonView(iconName: showPortfolio ? "plus" : "info")
                .animation(.none, value: showPortfolio)
                .onTapGesture {
                    if showPortfolio {
                        showPortfolioView.toggle()
                    } else {
                        showSettingView.toggle()
                    }
                }
                .background(
                    CircleButtonAnimationView(animate: $showPortfolio)
                )
            Spacer()
            Text(showPortfolio ? "Portfolio" : "Live Prices")
                .font(.headline)
                .fontWeight(.heavy)
                .foregroundStyle(Color.theme.accent)
                .animation(.none, value: showPortfolio)
            Spacer()
            CircleButtonView(iconName: "chevron.right")
                .rotationEffect(Angle(degrees: showPortfolio ? 180 : 0))
                .onTapGesture {
                    withAnimation(.spring) {
                        showPortfolio.toggle()
                    }
                }
        }
        .padding(.horizontal)
    }

    private var allCoinsList: some View {
        List {
            ForEach(vm.allCoins) { coin in
                // 由于NavigationLink会一次性全部加在，性能消耗过大，所以采用OnTapGesture
                CoinRowView(coin: coin, showHoldingsColumn: false)
                    .listRowInsets(.init(top: 10, leading: 0, bottom: 10, trailing: 10)) // 重新定义rowPadding
                    .onTapGesture {
                        segue(coin: coin)
                    }
            }
        }
        .listStyle(.plain)
    }

    private var portfolioCoinsList: some View {
        List {
            ForEach(vm.portfolioCoins) { coin in
                CoinRowView(coin: coin, showHoldingsColumn: true)
                    .listRowInsets(.init(top: 10, leading: 0, bottom: 10, trailing: 10)) // 重新定义rowPadding
                    .onTapGesture {
                        segue(coin: coin)
                    }
            }
        }
        .refreshable {
            print("~~~refresh the data")
            vm.reloadData() // 下拉刷新
        }
        .listStyle(.plain)
    }

    /// 点击跳转到详情
    private func segue(coin: CoinModel) {
        selectedCoin = coin
        showDetailView.toggle()
    }

    private var columnTitle: some View {
        HStack {
            HStack(spacing: 4) {
                // 一起放在HStack 方便点击
                Text("Coin")
                Image(systemName: "chevron.down")
                    .opacity(vm.sortOption == .rank || vm.sortOption == .rankReversed ? 1 : 0)
                    .rotationEffect(Angle(degrees: vm.sortOption == .rank ? 0 : 180))
            }
            .onTapGesture {
                withAnimation {
                    vm.sortOption = vm.sortOption == .rank ? .rankReversed : .rank
                }
            }
            Spacer()

            if showPortfolio {
                HStack(spacing: 4) {
                    Text("Hodings")
                    Image(systemName: "chevron.down")
                        .opacity(vm.sortOption == .holdings || vm.sortOption == .holdingReversed ? 1 : 0)
                        .rotationEffect(Angle(degrees: vm.sortOption == .holdings ? 0 : 180))
                }
                .onTapGesture {
                    withAnimation {
                        vm.sortOption = vm.sortOption == .holdings ? .holdingReversed : .holdings
                    }
                }
            }
            HStack(spacing: 4) {
                Text("Price")
                    .frame(width: UIScreen.main.bounds.width / 3.5, alignment: .trailing)
                Image(systemName: "chevron.down")
                    .opacity(vm.sortOption == .price || vm.sortOption == .priceReversed ? 1 : 0)
                    .rotationEffect(Angle(degrees: vm.sortOption == .price ? 0 : 180))
            }
            .onTapGesture {
                withAnimation {
                    vm.sortOption = vm.sortOption == .price ? .priceReversed : .price
                }
            }

            Button(action: {
                withAnimation {
                    vm.reloadData()
                }
            }, label: {
                Image(systemName: "goforward")
            })
            .rotationEffect(Angle(degrees: vm.isLoading ? 360 : 0), anchor: .center)
        }
        .font(.caption)
        .foregroundStyle(Color.theme.secondaryText)
        .padding(.horizontal)
    }
}
